/*
Copyright 2008, 2009 Joonas Lehtolahti

This file is part of Shared Datatypes and Utilities.

Shared Datatypes and Utilities is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Shared Datatypes and Utilities is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with Shared Datatypes and Utilities.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <stdio.h>
#include "prqueue.h"

int struct_first_cmp(int *a, int *b) {
	return *a-*b;
}

DLLEXPORT(PQueue*) newPQueue(CMPFUNC *cmpfunc) {
	PQueue *q = (PQueue *)malloc(sizeof(PQueue));
	if (!cmpfunc) cmpfunc = (CMPFUNC*)struct_first_cmp;
	q->q = LLcreate();
	q->cmpfunc = cmpfunc;
	return q;
}

DLLEXPORT(ListNode*) PQueueInsert(PQueue* q, void *data) {
	if (q && data) {
		CMPFUNC *func = q->cmpfunc;
		LinkedList *ql = q->q;
		ListNode *qn = ql->first;
		while (qn) {
			void *cdata = qn->x;
			if (func(data, cdata)>0) {
				qn = qn->next;
			}
			else return LLaddBefore(qn, data);
		}
		return LLaddLast(ql, data);
	}
	return NULL;
}

DLLEXPORT(void *) PQueuePeek(PQueue *q) {
	if (q) {
		ListNode *first = q->q->first;
		if (first) return first->x;
	}
	return NULL;
}

DLLEXPORT(void *) PQueuePoll(PQueue *q) {
	if (q) {
		return LLdelFirst(q->q);
	}
	return NULL;
}

DLLEXPORT(void *) PQueueCancel(PQueue *q, void *data) {
	if (q && data) {
		CMPFUNC *func = q->cmpfunc;
		LinkedList *ql = q->q;
		ListNode *qn = ql->first;
		while (qn) {
			void *cdata = qn->x;
			if (func(data,cdata)==0) {
				return LLdelNode(qn);
			}
			qn = qn->next;
		}
	}
	return NULL;
}

DLLEXPORT(void *) PQueueFind(PQueue *q, void *data) {
	if (q && data) {
		CMPFUNC *func = q->cmpfunc;
		LinkedList *ql = q->q;
		ListNode *qn = ql->first;
		while (qn) {
			void *cdata = qn->x;
			if (func(data,cdata)==0) {
				return cdata;
			}
			qn = qn->next;
		}
	}
	return NULL;
}
